package com.lagou.handler;

import com.lagou.pojo.RpcRequest;
import com.lagou.pojo.RpcResponse;
import com.lagou.server.UserServiceImpl;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class RpcServerHandler extends ChannelInboundHandlerAdapter{
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 如果符合规定则调用本地方法，返回数据   //UserService#SayHello#Are u Ok;
        // 1.判断当前是否符合规则
        if(msg.toString().startsWith("UserService")){
            // 2. 如果符合规则，调用实现类得到一个result
            String result = new UserServiceImpl().sayHello(msg.toString().substring(msg.toString().lastIndexOf("#") + 1));
            // 3.把调用实现类的方法获取的结果写到客户端
            ctx.writeAndFlush(result);
        }else{
            RpcRequest request = (RpcRequest) msg;
            RpcResponse response = new RpcResponse();
            response.setRequestId(request.getRequestId());
            response.setResult(handler(request));

            ctx.writeAndFlush(response);
        }
    }

    private Object handler(RpcRequest request) {
        return request.toString();
    }

}
